<template>
  <video ref="videoRef" :src="src" controls></video>
</template>

<script setup>
import { ref, onMounted } from 'vue';

const props = defineProps({
  src: {
    type: String,
    default: ''
  },
  currentTime: {
    type: Number,
    default: 0
  },
  isPlaying: {
    type: Boolean,
    default: false
  },
  diff: {
    type: String,
    default: 0
  }
});

const videoRef = ref(null);

const syncTime = (time) => {
  // 计算当前视频播放时间和传入时间的差值
  time = time + parseFloat(props.diff);
  if (videoRef.value) {
    const diff = Math.abs(videoRef.value.currentTime - time);
    // 如果差值超过 5 秒，则同步时间
    if (diff > 5) {
      videoRef.value.currentTime = time;
    }
  }
};

const play = () => {
  if (videoRef.value) {
    videoRef.value.muted = true;
    // 新增：播放视频
    videoRef.value.play().catch((error) => {
      console.error('播放视频失败:', error);
    });
  }
};

const pause = () => {
  if (videoRef.value && props.isPlaying) {
    videoRef.value.pause();
  }
};

onMounted(() => {
  play()
});

defineExpose({
  syncTime,
  play,
  pause
});
</script>

<style scoped>
video {
  width: 100%;
  margin: 0 auto;
  display: block;
}
</style>